<template>
  <div class="home-container">
    <!-- 功能导览提示 -->
    <div
      v-if="showDriver"
      class="driver-overlay"
    ></div>

    <!-- 搜索和操作区域 -->
    <div
      class="search-operate-area"
      ref="searchAreaRef"
    >
      <el-card class="search-card">
        <el-form
          :model="searchForm"
          inline
        >
          <el-form-item label="关键词搜索">
            <el-input
              v-model="searchForm.keyword"
              placeholder="请输入搜索关键词"
              style="width: 300px"
              ref="searchInputRef"
              @keyup.enter="handleSearch"
            >
              <template #append>
                <el-button
                  :icon="Search"
                  @click="handleSearch"
                />
              </template>
            </el-input>
          </el-form-item>

          <el-form-item label="状态">
            <el-select
              v-model="searchForm.status"
              placeholder="请选择状态"
            >
              <el-option
                label="全部"
                value=""
              />
              <el-option
                label="启用"
                value="active"
              />
              <el-option
                label="禁用"
                value="inactive"
              />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button
              type="primary"
              @click="handleSearch"
              >搜索</el-button
            >
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <el-card class="operate-card">
        <div class="operate-buttons">
          <el-button
            type="primary"
            :icon="Plus"
            @click="handleAdd"
            ref="addButtonRef"
          >
            添加数据
          </el-button>
          <el-button
            :icon="Guide"
            @click="startTour"
          >
            功能导览
          </el-button>
        </div>
      </el-card>
    </div>

    <!-- 数据表格区域 -->
    <div
      class="table-area"
      ref="tableAreaRef"
    >
      <el-card>
        <el-table
          :data="tableData"
          v-loading="loading"
          style="width: 100%"
          ref="tableRef"
        >
          <el-table-column
            type="index"
            label="序号"
            width="60"
          />
          <el-table-column
            prop="id"
            label="ID"
            width="80"
          />
          <el-table-column
            prop="name"
            label="名称"
            min-width="150"
          />
          <el-table-column
            prop="description"
            label="描述"
            min-width="200"
            show-overflow-tooltip
          />
          <el-table-column
            prop="status"
            label="状态"
            width="100"
          >
            <template #default="{ row }">
              <el-tag :type="row.status === 'active' ? 'success' : 'danger'">
                {{ row.status === "active" ? "启用" : "禁用" }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
            prop="createTime"
            label="创建时间"
            width="180"
          />
          <el-table-column
            label="操作"
            width="180"
            fixed="right"
            ref="actionColumnRef"
          >
            <template #default="{ row }">
              <el-button
                size="small"
                @click="handleDetail(row)"
                ref="detailButtonRef"
              >
                详情
              </el-button>
              <el-button
                size="small"
                type="danger"
                @click="handleDelete(row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>

    <!-- 分页区域 -->
    <div
      class="pagination-area"
      ref="paginationAreaRef"
    >
      <el-card>
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="数据详情"
      width="600px"
      ref="detailDialogRef"
    >
      <div v-if="currentDetail">
        <el-descriptions
          :column="2"
          border
        >
          <el-descriptions-item label="ID">{{
            currentDetail.id
          }}</el-descriptions-item>
          <el-descriptions-item label="名称">{{
            currentDetail.name
          }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag
              :type="currentDetail.status === 'active' ? 'success' : 'danger'"
            >
              {{ currentDetail.status === "active" ? "启用" : "禁用" }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">{{
            currentDetail.createTime
          }}</el-descriptions-item>
          <el-descriptions-item
            label="描述"
            :span="2"
          >
            {{ currentDetail.description }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Search, Plus, Guide } from "@element-plus/icons-vue";
import { driver } from "driver.js";
import "driver.js/dist/driver.css";

// 类型定义
interface SearchForm {
  keyword: string;
  status: string;
}

interface TableData {
  id: number;
  name: string;
  description: string;
  status: string;
  createTime: string;
}

interface Pagination {
  currentPage: number;
  pageSize: number;
  total: number;
}

// 响应式数据
const searchForm = reactive<SearchForm>({
  keyword: "",
  status: "",
});

const tableData = ref<TableData[]>([]);
const loading = ref(false);
const detailDialogVisible = ref(false);
const currentDetail = ref<TableData | null>(null);
const showDriver = ref(false);

const pagination = reactive<Pagination>({
  currentPage: 1,
  pageSize: 10,
  total: 0,
});

// DOM 引用
const searchAreaRef = ref<HTMLElement>();
const searchInputRef = ref();
const addButtonRef = ref();
const tableAreaRef = ref<HTMLElement>();
const tableRef = ref();
const actionColumnRef = ref();
const detailButtonRef = ref();
const paginationAreaRef = ref<HTMLElement>();
const detailDialogRef = ref();

// Driver.js 实例
let driverObj: any = null;

// 初始化数据
const initTableData = () => {
  // 模拟数据
  const mockData: TableData[] = [];
  for (let i = 1; i <= 50; i++) {
    mockData.push({
      id: i,
      name: `数据项 ${i}`,
      description: `这是第 ${i} 个数据项的详细描述信息，用于演示功能`,
      status: i % 3 === 0 ? "inactive" : "active",
      createTime: new Date(Date.now() - i * 86400000).toLocaleString(),
    });
  }
  tableData.value = mockData;
  pagination.total = mockData.length;
};

// 搜索处理
const handleSearch = () => {
  pagination.currentPage = 1;
  loadTableData();
};

const handleReset = () => {
  searchForm.keyword = "";
  searchForm.status = "";
  pagination.currentPage = 1;
  loadTableData();
};

// 加载表格数据
const loadTableData = () => {
  loading.value = true;
  // 模拟 API 调用延迟
  setTimeout(() => {
    initTableData();
    loading.value = false;
  }, 500);
};

// 添加数据
const handleAdd = () => {
  ElMessage.success("点击了添加按钮");
  // 这里可以打开添加对话框
};

// 查看详情
const handleDetail = (row: TableData) => {
  currentDetail.value = row;
  detailDialogVisible.value = true;
};

// 删除数据
const handleDelete = (row: TableData) => {
  ElMessageBox.confirm(`确定要删除 "${row.name}" 吗？`, "删除确认", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      ElMessage.success("删除成功");
      loadTableData();
    })
    .catch(() => {
      ElMessage.info("取消删除");
    });
};

// 分页处理
const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.currentPage = 1;
  loadTableData();
};

const handleCurrentChange = (page: number) => {
  pagination.currentPage = page;
  loadTableData();
};

// Driver.js 功能导览
const startTour = () => {
  showDriver.value = true;

  driverObj = driver({
    showProgress: true,
    animate: true,
    overlayOpacity: 0.5,
    steps: [
      {
        element: addButtonRef.value?.$el,
        popover: {
          title: "添加数据",
          description: "点击这里可以添加新的数据记录",
          side: "bottom",
          align: "start",
        },
      },
      {
        element: searchInputRef.value?.$el,
        popover: {
          title: "搜索数据",
          description: "在这里输入关键词来搜索您需要的数据",
          side: "bottom",
          align: "start",
        },
      },
      {
        element: tableAreaRef.value,
        popover: {
          title: "数据表格",
          description: "这里展示所有的数据记录，您可以查看和管理数据",
          side: "top",
          align: "center",
        },
      },
      {
        element: detailButtonRef.value?.$el,
        popover: {
          title: "查看详情",
          description: "点击详情按钮可以查看数据的完整信息",
          side: "left",
          align: "start",
        },
      },
      {
        element: paginationAreaRef.value,
        popover: {
          title: "分页导航",
          description: "使用分页控件来浏览更多数据页面",
          side: "top",
          align: "center",
        },
      },
    ],
    onDestroyed: () => {
      showDriver.value = false;
    },
  });

  driverObj.drive();
};

// 生命周期
onMounted(() => {
  loadTableData();

  // 检查是否是首次访问，如果是则自动开始导览
  const hasVisited = localStorage.getItem("hasVisitedHome");
  if (!hasVisited) {
    setTimeout(() => {
      startTour();
      localStorage.setItem("hasVisitedHome", "true");
    }, 1000);
  }
});
</script>

<style scoped>
.home-container {
  padding: 20px;
  position: relative;
}

.driver-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 9998;
  pointer-events: none;
}

.search-operate-area {
  margin-bottom: 20px;
}

.search-card {
  margin-bottom: 16px;
}

.operate-buttons {
  display: flex;
  gap: 12px;
}

.table-area {
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  padding: 16px 0;
}

:deep(.driver-popover) {
  border-radius: 8px;
}

:deep(.driver-popover-title) {
  font-size: 16px;
  font-weight: bold;
}

:deep(.driver-popover-description) {
  font-size: 14px;
  line-height: 1.5;
}
</style>
